package indi.zjh.dp.util;

import indi.zjh.dp.orm.Business;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import net.sf.json.JSONObject;

import org.msgpack.MessagePack;

public class SerializeUtil {
	
	private static MessagePack msgpack = new MessagePack();

	public static void register(Class<?> cls)
	{
		//System.out.println("register "+cls.getName());
		msgpack.register(cls);
	}

	public static byte[] serialize(Object object) 
	{  
		ObjectOutputStream oos = null;  
		ByteArrayOutputStream baos = null;  
		try {  
			//序列化  
			baos = new ByteArrayOutputStream();  
			oos = new ObjectOutputStream(baos); 
			oos.writeObject(object);  
			byte[] bytes = baos.toByteArray();  
			return bytes;  
		} catch (Exception e) {
			e.printStackTrace();
		}  
		return null;  
	}  
	
//	public static byte[] serialize(Object object) 
//	{  
//		JSONObject jobj = JSONObject.fromObject(object);
//		return jobj.toString().getBytes();
//	}  

//	public static byte[] serialize(Object object) throws IOException 
//	{  
//		return msgpack.write(object);
//	}  
	
	public static Object unserialize(byte[] bytes, Class<?> cls) 
	{
		ByteArrayInputStream bais = null;  
		try {
			//反序列化  
			bais = new ByteArrayInputStream(bytes);  
			ObjectInputStream ois = new ObjectInputStream(bais);  
			return ois.readObject();  
		} catch (Exception e) {
			e.printStackTrace();
		}  
		return null;  
	}
	
//	public static Object unserialize(byte[] bytes, Class<?> cls) 
//	{
//		String data = new String(bytes);
//		JSONObject jobj = JSONObject.fromObject(data);
//		return JSONObject.toBean(jobj, cls);
//	}
	
//	public static Object unserialize(byte[] bytes, Class<?> cls) throws IOException 
//	{
//		return msgpack.read(bytes, cls);
//	}
}  
